//
//  Allocator.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/6.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

struct Allocator {
    /// 使用calloc动态分配内存
    /// 使用UnsafeMutablePointer.allocate需要初始化比较麻烦
    /// Note: 使用完需要回收
    static func allocate<_Tp>(_ capacity: Int, for type: _Tp.Type) -> UnsafeMutablePointer<_Tp> {
        guard let pointer = calloc(capacity, MemoryLayout<_Tp>.size) else {
            fatalError("could not allocate memory")
        }
        return pointer.bindMemory(to: type, capacity: capacity)
    }
}
